package com.sunny.excel.config.resolver;

import com.sunny.excel.dto.Tuple2;
import com.sunny.excel.enumeration.BizErrorEnum;
import com.sunny.excel.exception.BizException;
import com.sunny.excel.annotation.MultiSheetExcelFile;
import com.sunny.excel.excel.uploader.ExcelUploadManager;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author:shucq
 * @Description:
 * @Date 2019/10/28 15:18
 */
public class MultiSheetExcelFileArgumentResolver implements HandlerMethodArgumentResolver {
    @Autowired private ExcelUploadManager excelUploadManager;

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterAnnotation(MultiSheetExcelFile.class) != null;
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
        NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        MultiSheetExcelFile multiSheetExcelFile = parameter.getParameterAnnotation(MultiSheetExcelFile.class);
        Map<Tuple2<Integer, Class<?>>, List<?>> result = new LinkedHashMap<>();
        try {
            MultipartRequest request = webRequest.getNativeRequest(MultipartRequest.class);
            MultipartFile file = request.getFile(multiSheetExcelFile.value());
            for (int sheetIndex = 0; sheetIndex < multiSheetExcelFile.dataClasses().length; sheetIndex++) {
                Class<?> dataClass = multiSheetExcelFile.dataClasses()[sheetIndex];
                String fileExt = FilenameUtils.getExtension(file.getOriginalFilename());
                List<?> records = excelUploadManager.process(fileExt, file.getInputStream(), sheetIndex, dataClass);
                result.put(new Tuple2<>(sheetIndex, dataClass), records);
            }
            return result;
        } catch (Exception ex) {
            throw new BizException(BizErrorEnum.UPLOAD_ERROR,ex);
        }
    }
}

